package com.bwie.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.domain.TOrder;
import com.bwie.domain.TProduct;
import com.bwie.service.TProductService;
import com.bwie.mapper.TProductMapper;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;

/**
* @author 36167
* @description 针对表【t_product(商品表)】的数据库操作Service实现
* @createDate 2025-03-12 09:56:25
*/
@Service
public class TProductServiceImpl extends ServiceImpl<TProductMapper, TProduct>
    implements TProductService{

    @Autowired
    private TProductMapper tProductMapper;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Override
    public R prodlist(PageInfoVo pageInfoVo) {
        Integer pageNum=0;

        if (pageInfoVo.getPageNum()>0){
            pageNum=pageInfoVo.getPageNum()-1;
        }

        PageRequest pageRequest=PageRequest.of(pageNum,pageInfoVo.getPageSize());

        BoolQueryBuilder builder = new BoolQueryBuilder();
        if (!StringUtils.isEmpty(pageInfoVo.getKeyWord())){
            builder.should(QueryBuilders.matchQuery("name",pageInfoVo.getKeyWord()));
        }else {
            builder.must(QueryBuilders.matchAllQuery());
        }

        NativeSearchQueryBuilder nati = new NativeSearchQueryBuilder();
        nati.withQuery(builder).withPageable(pageRequest);

        SearchHits<TProduct> search = restTemplate.search(nati.build(), TProduct.class);
        ArrayList<TProduct> list = new ArrayList<>();
        long total = search.getTotalHits();
        for (SearchHit<TProduct> searchHit : search) {
            TProduct content = searchHit.getContent();
            list.add(content);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("list",list);
        return R.OK(map);
    }


}




